# import grpc
from concurrent import futures
# import torch
# import multiprocessing
from concurrent.futures import ProcessPoolExecutor
# import vad_pb2
# import vad_pb2_grpc
from collections import defaultdict
# import logging
import numpy as np

from silero_vad.model import load_silero_vad
from silero_vad.utils_vad import (get_speech_timestamps, VADIterator,read_pcm)  # 导入 get_speech_timestamps
USE_ONNX = False # change this to True if you want to test onnx model

# from silero_vad import (load_silero_vad,
#                           read_audio,
#                           get_speech_timestamps,
#                           save_audio,
#                           VADIterator,
#                           collect_chunks)
model = load_silero_vad(onnx=USE_ONNX)
# wav = read_pcm('by.pcm', sampling_rate=16000)
# # get speech timestamps from full audio file
# speech_timestamps = get_speech_timestamps(wav, model, sampling_rate=16000)
# print(speech_timestamps)
def read_pcm_file(file_path, chunk_size, sampling_rate):
    """
    Read PCM file in chunks
    """
    with open(file_path, 'rb') as f:
        while True:
            chunk = f.read(chunk_size * 2)  # 16-bit PCM, 2 bytes per sample
            if len(chunk) < chunk_size * 2:
                break
            audio_int16 = np.frombuffer(chunk, dtype=np.int16)
            audio_float32 = (audio_int16 / 32768.0).astype(np.float32)
            yield audio_float32
            
vad_iterator = VADIterator(model=model,
                            threshold=0.5,
                            sampling_rate=16000,
                            min_silence_duration_ms=60,
                            speech_pad_ms=30)
for audio_chunk in read_pcm_file("test.pcm", 512, 16000):
    result = vad_iterator(audio_chunk, return_seconds=True)
    if result:
        print(result)

print("Processing complete.")
